package com.robot.ble

import android.Manifest.permission
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.base.util.alert

class SplashActivity : AppCompatActivity() {
    private lateinit var permissionLaunch: ActivityResultLauncher<Array<String>>
    private val builder = StringBuilder()

    private val _arrayPermission = arrayOf(
        permission.READ_PHONE_STATE,
        permission.CAMERA,
        permission.WRITE_EXTERNAL_STORAGE,
        permission.READ_EXTERNAL_STORAGE,
        permission.ACCESS_FINE_LOCATION,
        permission.ACCESS_COARSE_LOCATION,
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        permissionLaunch =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { map ->
                val filterMap = map.filter { !it.value }
                filterMap.forEach {
                    val key = it.key
                    when {
                        TextUtils.equals(permission.READ_PHONE_STATE, key) ->
                            builder.append("手机状态权限、")
                        TextUtils.equals(permission.CAMERA, key) ->
                            builder.append("相机权限、")
                        TextUtils.equals(permission.READ_EXTERNAL_STORAGE, key) ->
                            builder.append("存储权限、")
                        TextUtils.equals(permission.ACCESS_COARSE_LOCATION, key) ->
                            builder.append("定位权限、")
                    }
                }
                onMultipleCallback()
            }
        permissionLaunch.launch(_arrayPermission)
    }

    private fun onMultipleCallback() {
        if (!TextUtils.isEmpty(builder)) {
            alert(
                "请开启$builder", { dialog, _ ->
                    dialog?.dismiss()
                    startActivity(Intent(Settings.ACTION_SETTINGS)) //直接进入手机中设置界面
                    finish()
                },
                false
            )
            return
        }
        //Android6.0以上
        /*if (!DeviceUtil.hasOverlaysPermission(this)) {
            showPermissionNextDialog(
                "请授予悬浮窗权限", { dialog, _, _ ->
                    dialog?.dismiss()
                    grantOverlays(overlaysLaunch)
                },
                false
            )
            return
        }
        startService(Intent(this, LocalService::class.java))
        checkInstall()*/
        startActivity(Intent(this, MainActivity::class.java))
    }
}